package com.gitee.feizns.quickstart.mybatis.flex.query;

import com.gitee.feizns.dynamic.bean.Getter;
import com.gitee.feizns.dynamic.bean.Props;
import com.gitee.feizns.dynamic.reflect.Lambdas;
import com.mybatisflex.core.table.TableInfo;
import com.mybatisflex.core.table.TableInfoFactory;
import com.mybatisflex.core.util.FieldWrapper;
import lombok.SneakyThrows;

import java.lang.invoke.SerializedLambda;

/**
 * Lambda 解析
 * @author feizns
 * @since 2025/9/23
 */
@lombok.Getter
public class LambdaColumnParser<T> {

    /**
     * 实体类
     */
    private final Class<T> entityClass;

    /**
     * column
     */
    private final Getter<T, ?> getter;

    /**
     * 序列化 lambda
     */
    private final SerializedLambda serializedLambda;

    /**
     * 表信息
     */
    private final TableInfo tableInfo;

    /**
     * 属性名称
     */
    private final String propertyName;

    /**
     * 字段
     */
    private final FieldWrapper fieldWrapper;

    /**
     * lambda 列
     * @param getter 吸气剂
     */
    @SneakyThrows
    public LambdaColumnParser(Getter<T, ?> getter) {
        this.getter = getter;
        this.serializedLambda = Lambdas.getSerializedLambda(getter);
        //noinspection unchecked
        this.entityClass = (Class<T>) Class.forName(serializedLambda.getImplClass().replace("/", "."));
        this.tableInfo = TableInfoFactory.ofEntityClass(entityClass);
        this.propertyName = Props.name(serializedLambda.getImplMethodName());
        this.fieldWrapper = FieldWrapper.of(entityClass, propertyName);
    }

    /**
     * 之
     * @param getter 吸气剂
     * @return {@link LambdaColumnParser }<{@link T }>
     */
    public static <T> LambdaColumnParser<T> of(Getter<T, ?> getter) {
        return new LambdaColumnParser<>(getter);
    }

    /**
     * 获取列名称
     * @return {@link String }
     */
    public String getColumnName() {
        return tableInfo.getColumnByProperty(propertyName);
    }

}
